package com.liaoyin.travel.service.approval;

import com.liaoyin.travel.view.moble.approval.ApprovalIsVisibleBackView;
import com.liaoyin.travel.view.moble.approval.ApprovalIsVisibleView;
import com.liaoyin.travel.view.user.UserView;
import com.liaoyin.travel.vo.approval.InsertOrUpdateApprovalVisualRangeVo;
import com.liaoyin.travel.base.constant.VariableConstants;
import com.liaoyin.travel.base.service.BaseService;
import com.liaoyin.travel.bean.UserInfo;
import com.liaoyin.travel.dao.approval.ApprovalVisualRangeSettingMapper;
import com.liaoyin.travel.entity.approval.ApprovalVisualRangeSetting;
import com.liaoyin.travel.entity.approval.AskForLeaveVisibleUser;
import com.liaoyin.travel.entity.approval.CardReissueVisibleUser;
import com.liaoyin.travel.entity.approval.GoOutVisibleUser;
import com.liaoyin.travel.exception.BusinessException;
import com.liaoyin.travel.service.UsersService;
import com.liaoyin.travel.util.PartyUtil;
import com.liaoyin.travel.util.SnowIdUtil;
import com.liaoyin.travel.util.StringUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 审批-可见范围设置
 *
 * @author kuang.jiazhuo
 * @date 2019-11-21 09:41
 */
@Service
public class VisualRangeSettingService extends BaseService<ApprovalVisualRangeSettingMapper, ApprovalVisualRangeSetting> {


    @Resource
    AskForLeaveVisibleUserService askForLeaveVisibleUserService;

    @Resource
    CardReissueVisibleUserService cardReissueVisibleUserService;

    @Resource
    GoOutVisibleUserService goOutVisibleUserService;

    @Resource
    UsersService usersService;

    /**
     * @方法名：insertOrUpdateApprovalVisualRangeSetting
     * @描述： 新增或修改【审批-可见范围设置】
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/21 10:10
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertOrUpdateApprovalVisualRangeSetting(InsertOrUpdateApprovalVisualRangeVo insertOrUpdateApprovalVisualRangeVo) {
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if(curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();

        int result = 0;
        String id = insertOrUpdateApprovalVisualRangeVo.getApprovalVisualRangeId();
        String visualRange = insertOrUpdateApprovalVisualRangeVo.getVisualRange();
        String everyMenIds = insertOrUpdateApprovalVisualRangeVo.getEveryMenIds();
        System.err.println("everyMenIds="+everyMenIds);
        //有效性验证
        if(VariableConstants.STRING_CONSTANT_2.equals(visualRange)){
            //部分选中可见，则必须选择可见人
            if(StringUtil.isBlank(everyMenIds)){
                throw new BusinessException("visible.person.is.not.chosen");
            }
        }

        //审批类型
        String approvalType = insertOrUpdateApprovalVisualRangeVo.getApprovalType();
        ApprovalVisualRangeSetting approvalVisualRangeSetting = new ApprovalVisualRangeSetting();
        if(id==null){
          /** 新增*/

            approvalVisualRangeSetting
                    .setId(SnowIdUtil.getInstance().nextId())
                    .setIsUsing(VariableConstants.STRING_CONSTANT_1)
                    .setCreateTime(LocalDateTime.now())
                    .setIsDelete(VariableConstants.STRING_CONSTANT_0)
                    .setVisualRange(visualRange)
                    .setApprovalType(approvalType)
                    //景区id
                    .setScenicId(scenicId);
            if(VariableConstants.STRING_CONSTANT_2.equals(visualRange)){
                String[] everyMenIdStrArray = everyMenIds.split(",");
                List<String> everyMenIdList = Arrays.asList(id);

                //补卡申请
                if(VariableConstants.STRING_CONSTANT_1.equals(approvalType)){
                    this.cardReissueVisibleUserService.insertOrUpdateApprovalCardReissueVisible(everyMenIdList,1);
                }
                //请假申请
                if(VariableConstants.STRING_CONSTANT_2.equals(approvalType)){
                    this.askForLeaveVisibleUserService.insertOrUpdateApprovalAskForLeaveVisibleUser(everyMenIdList,1);
                }
                //外出申请
                if(VariableConstants.STRING_CONSTANT_3.equals(approvalType)){
                    this.goOutVisibleUserService.insertOrUpdateApprovalGoOutVisibleUser(everyMenIdList,1);
                }

            }
            result = this.mapper.insertSelective(approvalVisualRangeSetting);
        }else{
          /** 更新*/
            if(VariableConstants.STRING_CONSTANT_2.equals(visualRange)){
                String[] everyMenIdStrArray = everyMenIds.split(",");
                List<String> everyMenIdList = Arrays.asList(everyMenIdStrArray);

                //补卡申请
                if(VariableConstants.STRING_CONSTANT_1.equals(approvalType)){
                    this.cardReissueVisibleUserService.insertOrUpdateApprovalCardReissueVisible(everyMenIdList,2);
                }
                //请假申请
                if(VariableConstants.STRING_CONSTANT_2.equals(approvalType)){
                    this.askForLeaveVisibleUserService.insertOrUpdateApprovalAskForLeaveVisibleUser(everyMenIdList,2);
                }
                //外出申请
                if(VariableConstants.STRING_CONSTANT_3.equals(approvalType)){
                    this.goOutVisibleUserService.insertOrUpdateApprovalGoOutVisibleUser(everyMenIdList,2);
                }

            }
            approvalVisualRangeSetting.setId(id);
            approvalVisualRangeSetting.setVisualRange(visualRange);
            System.err.println("approvalVisualRangeSetting="+approvalVisualRangeSetting);
          result = this.mapper.updateByPrimaryKeySelective(approvalVisualRangeSetting);
        }
        return result;
    }

    /**
     * @方法名：whetherTheApprovalIsVisible
     * @描述： 用户传入请求类型，查询自己的审批可见范围
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/22 15:21
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean whetherTheApprovalIsVisible(String approvalType) {
        boolean isVisible = false;
        //判断用户是否登录,顺便获取到用户的登录信息
        UserInfo user = PartyUtil.getCurrentUserInfo();
        if(user == null) {
            throw new BusinessException("user.isNotLogin");
        }
        String userId = user.getId();
        //查询审批范围的设置信息
        ApprovalVisualRangeSetting visualRangeSetting = this.mapper.selectApprovalVisualRangeSettingByApprovalType(approvalType);
        if(visualRangeSetting==null){
            throw new BusinessException("did.not.find.visualRangeSetting");
        }
        String visualRange = visualRangeSetting.getVisualRange();
        if(VariableConstants.STRING_CONSTANT_1.equals(visualRange)){
            /** 全部范围可见 */
            isVisible = true;
        }else{
            /** 部分员工可见*/
            int count = 0;
            //补卡
            if(VariableConstants.STRING_CONSTANT_1.equals(approvalType)){
                count = this.cardReissueVisibleUserService.countCardReissueVisibleUserByUserId(userId);
            }
            //请假
            if(VariableConstants.STRING_CONSTANT_2.equals(approvalType)){
                count = this.askForLeaveVisibleUserService.countAskForLeaveVisibleUserByUserId(userId);
            }
            //外出
            if(VariableConstants.STRING_CONSTANT_3.equals(approvalType)){
                count = this.goOutVisibleUserService.countGoOutVisibleUserByUserId(userId);
            }
            if(count>0){
                isVisible = true;
            }
        }
        return isVisible;
    }

    /**
     * @方法名：whetherTheApprovalIsVisibleByLoginUser
     * @描述： 登录用户查询自己的审批可见范围
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/23 12:09
     */
    public List<ApprovalIsVisibleView> whetherTheApprovalIsVisibleByLoginUser() {
        //判断用户是否登录,顺便获取到用户的登录信息
        UserInfo user = PartyUtil.getCurrentUserInfo();
        if(user == null) {
            throw new BusinessException("user.isNotLogin");
        }
        /** 景区id */
        String scenicId = user.getScenicId();

        String userId = user.getId();
        List<ApprovalIsVisibleView> approvalIsVisibleViewList = new ArrayList<>();
        //查询审批范围的设置信息
        List<ApprovalVisualRangeSetting> visualRangeSettingList = this.mapper.selectApprovalVisualRangeSettingByAll(scenicId);
        visualRangeSettingList.forEach(visualRangeSetting ->{
            ApprovalIsVisibleView approvalIsVisibleView = ApprovalIsVisibleView.builder().build();
            int count = 0;
            //审批类型
            String approvalType = visualRangeSetting.getApprovalType();
            //可见范围
            String visualRange = visualRangeSetting.getVisualRange();
            //是否启用
            String isUsing = visualRangeSetting.getIsUsing();
            //补卡
            if(VariableConstants.STRING_CONSTANT_1.equals(approvalType)){
                if(VariableConstants.STRING_CONSTANT_1.equals(isUsing)){
                    if(VariableConstants.STRING_CONSTANT_1.equals(visualRange)){
                        count = 1;
                    }else{
                        count = this.cardReissueVisibleUserService.countCardReissueVisibleUserByUserId(userId);
                    }
                }
                approvalIsVisibleView .setApprovalType(VariableConstants.STRING_CONSTANT_1);
            }
            //请假
            if(VariableConstants.STRING_CONSTANT_2.equals(approvalType)){
                if(VariableConstants.STRING_CONSTANT_1.equals(isUsing)){
                    if(VariableConstants.STRING_CONSTANT_1.equals(visualRange)){
                        count = 1;
                    }else{
                        count = this.askForLeaveVisibleUserService.countAskForLeaveVisibleUserByUserId(userId);
                    }
                }
                approvalIsVisibleView .setApprovalType(VariableConstants.STRING_CONSTANT_2);
            }
            //外出
            if(VariableConstants.STRING_CONSTANT_3.equals(approvalType)){
                if(VariableConstants.STRING_CONSTANT_1.equals(isUsing)){
                    if(VariableConstants.STRING_CONSTANT_1.equals(visualRange)){
                        count = 1;
                    }else{
                        count = this.goOutVisibleUserService.countGoOutVisibleUserByUserId(userId);
                    }
                }
                approvalIsVisibleView .setApprovalType(VariableConstants.STRING_CONSTANT_3);
            }
            boolean isVisible = count>0?true:false;
            approvalIsVisibleView.setVisible(isVisible);
            approvalIsVisibleViewList.add(approvalIsVisibleView);
        });

        return approvalIsVisibleViewList;
    }

    /**
     * @方法名：selectApprovalVisualRangeSettingByAll
     * @描述： 查询出所有的审批类型的可见范围
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/23 15:45
     */
    public List<ApprovalIsVisibleBackView> selectApprovalVisualRangeSettingByAll() {

        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if(curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();

        //查询所有的审批可见范围
        List<ApprovalVisualRangeSetting> approvalVisualRangeSettings = this.mapper.selectApprovalVisualRangeSettingByAll(scenicId);

        List<ApprovalIsVisibleBackView> approvalIsVisibleBackViewList = new ArrayList<>();
        if(approvalVisualRangeSettings!=null){
            approvalVisualRangeSettings.forEach(visualRange ->{
                List<UserView> visibleUsers = new ArrayList<>();
                String approvalType = visualRange.getApprovalType();
                //补卡
                if(VariableConstants.STRING_CONSTANT_1.equals(approvalType)){
                    List<CardReissueVisibleUser> list = this.cardReissueVisibleUserService.selectCardReissueVisibleUserByScenicId(scenicId);
                    list.forEach(visibleUser ->{
                        UserView userView = this.usersService.selectUserViewById(visibleUser.getUserId());
                        visibleUsers.add(userView);
                    });
                }
                //请假
                if(VariableConstants.STRING_CONSTANT_2.equals(approvalType)){
                    List<AskForLeaveVisibleUser> list = this.askForLeaveVisibleUserService.selectAskForLeaveVisibleUserByScenicId(scenicId);
                    list.forEach(visibleUser ->{
                        UserView userView = this.usersService.selectUserViewById(visibleUser.getUserId());
                        visibleUsers.add(userView);
                    });
                }
                //外出
                if(VariableConstants.STRING_CONSTANT_3.equals(approvalType)){
                    List<GoOutVisibleUser> list = this.goOutVisibleUserService.selectGoOutVisibleUserByScenicId(scenicId);
                    list.forEach(visibleUser ->{
                        UserView userView = this.usersService.selectUserViewById(visibleUser.getUserId());
                        visibleUsers.add(userView);
                    });

                }
                ApprovalIsVisibleBackView approvalIsVisibleBackView = new ApprovalIsVisibleBackView()
                        .setApprovalVisualRangeId(visualRange.getId())
                        .setIsVisible(visualRange.getVisualRange()).setIsVisibleDisplay(visualRange.getVisualRangeDisplay())
                        .setApprovalType(approvalType).setApprovalTypeDisplay(visualRange.getApprovalTypeDisplay())
                        .setIsUsing(visualRange.getIsUsing())
                        .setVisibleUsers(visibleUsers);
                approvalIsVisibleBackViewList.add(approvalIsVisibleBackView);
                    });
        }
        return approvalIsVisibleBackViewList;
    }

    /**
     * @方法名：usingOrDisableApprovalType
     * @描述： 启用或停用可见范围(停用了可见范围，移动端就查不到该审批类型,相当于停用)
     * @作者： Kuang.JiaZhuo
     * @日期： Created in 2019/11/23 16:11
     */
    public int usingOrDisableApprovalType(String onOff,String approvalType) {
        UserInfo curveUserInfo = PartyUtil.getCurrentUserInfo();
        if(curveUserInfo == null) {
            throw new BusinessException("not.login");
        }
        /** 景区id */
        String scenicId = curveUserInfo.getScenicId();

        int result = this.mapper.usingOrDisableApprovalType(onOff,approvalType,scenicId);
        return result;
    }

    /**
     * @方法名：insertVisualRangeSettingByScenicInfoId
     * @描述： 新建景区的审批可见范围
     * @作者： kjz
     * @日期： Created in 2020/2/24 0:50
     */
    @Transactional(rollbackFor = Exception.class)
    public int insertVisualRangeSettingByScenicInfoId(String scenicId) {

        List<ApprovalVisualRangeSetting> list = new ArrayList<>();
        for (int i = 1; i < 4; i++) {
            String id = scenicId+(i);
            ApprovalVisualRangeSetting approvalVisualRangeSetting = new ApprovalVisualRangeSetting()
                    .setId(id).setApprovalType(String.valueOf(i))
                    .setVisualRange(VariableConstants.STRING_CONSTANT_1)
                    .setIsUsing(VariableConstants.STRING_CONSTANT_1)
                    .setIsDelete(VariableConstants.STRING_CONSTANT_0)
                    .setCreateTime(LocalDateTime.now())
                    .setScenicId(scenicId);
            list.add(approvalVisualRangeSetting);

            //为了处理bug，先删除
            this.mapper.deleteApprovalVisualRangeSettingById(id);
        }
        return this.mapper.insertList(list);
    }
}
